// MvxWpfViewPresenter.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
// 
// Project Lead - Stuart Lodge, @slodge, me@slodge.com

using System;
using System.Collections.Generic;
using System.Windows;
using Cirrious.MvvmCross.ExtensionMethods;
using Cirrious.MvvmCross.Interfaces.ServiceProvider;
using Cirrious.MvvmCross.Interfaces.ViewModels;
using Cirrious.MvvmCross.Platform.Diagnostics;
using Cirrious.MvvmCross.Views;
using Cirrious.MvvmCross.Wpf.Interfaces;

namespace TeaLightV5.Foundation.UX.Wpf.MvvmCross.Views
{
    public abstract class TeaWpfViewPresenter
        : IMvxWpfViewPresenter
        , IMvxServiceConsumer
    {
        private Stack<MvxShowViewModelRequest>  _requests = new Stack<MvxShowViewModelRequest>();

        public void Show(MvxShowViewModelRequest request)
        {
            try
            {
                var loader = this.GetService<IMvxSimpleWpfViewLoader>();
                var view = loader.CreateView(request);
                _requests.Push(request);
                Present(view);
            }
            catch (Exception exception)
            {
                MvxTrace.Trace("Error seen during navigation request to {0} - error {1}", request.ViewModelType.Name,
                               exception.ToLongString());
            }
        }

        public abstract void Present(FrameworkElement frameworkElement);

        public void Close(IMvxViewModel viewModel)
        {
            Back();
        }

        public void Back()
        {
            if (_requests.Count <= 1)
            {
                //throw new Exception("What to do?");
                // do nothing
                return;
            }
            // pop current
            _requests.Pop();
            // pop previous
            MvxShowViewModelRequest request = _requests.Pop();
            Show(request);
        }
    }
}